import { setTimeout } from "timers";

//扑克逻辑
cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //    default: null,
        //    url: cc.Texture2D,  // optional, default is typeof default
        //    serializable: true, // optional, default is true
        //    visible: true,      // optional, default is true
        //    displayName: 'Foo', // optional
        //    readonly: false,    // optional, default is false
        // },
        // ...
        bet: {
            default: null,
            type: cc.Node
        },

        _seats: [],
        _timeLabel: null,
        _voiceMsgQueue: [],
        _lastPlayingSeat: null,
        _playingSeat: null,
        _lastPlayTime: null,
        _jishi: false,
        _kaiShi: null,
        _guoZhuang: null,
        _kaiZhuangPai: null,
        _shangZhuang: null,
        _state: null,
        _lblTime: null,
        // _zhuNum: 0,
        _seatsResult: [],
        _randomCard: [],
        _zhuma: null

    },

    // use this for initialization
    onLoad: function () {
        if (cc.vv == null) {
            return;
        }
        if (!cc.sys.isNative && cc.sys.isMobile) {
            var cvs = this.node.getComponent(cc.Canvas);
            cvs.fitHeight = true;
            cvs.fitWidth = true;
        }
        if (!cc.vv) {
            cc.director.loadScene("loading");
            return;
        }

        cc.vv.audioMgr.playBGM("bgFight.mp3");
        this.addComponent("TimePointer");
        // this.addComponent("GameResult");
        // this.addComponent("GameOver");   

        this.addComponent("Common");
        // this.addComponent("ReplayCtrl");
        this.addComponent("Chat");
        this.addComponent("PopupMgr");
        this.addComponent("ReConnect");
        this.addComponent("Voice");
        this.addComponent("UserInfoShow");
        this.addComponent("GameResult");


        this.initView();
        cc.vv.common.initSeats();
        this.initEventHandlers();


    },

    initView: function () {
        this._kaiShi = cc.find("Canvas/arrow/kaishi");
        this._guoZhuang = cc.find("Canvas/arrow/guozhuang");
        this._kaiZhuangPai = cc.find("Canvas/arrow/kaizhuangpai");
        this._shangZhuang = cc.find("Canvas/arrow/shangzhuang");
        this._zhuangPai = cc.find("Canvas/arrow/zhuangpai");
        this._state = cc.find("Canvas/arrow/dengdai")
        this._lblTime = cc.find("Canvas/arrow/lblTime").getComponent(cc.Label);
        this._zhuma = cc.find("Canvas/bet/zhuma");

        var _this = this;
        if (cc.vv.replayMgr.isReplay()) {
            setTimeout(function () {
                _this.showAction(cc.vv.gameNetMgr.cards);
                var resultslist = cc.vv.gameNetMgr.resultslist;
                var erguo = cc.find("Canvas/bet/betPos/poserguo/selfZhu").getComponent(cc.Label);
                var duimen = cc.find("Canvas/bet/betPos/posduimen/selfZhu").getComponent(cc.Label);
                var sifan = cc.find("Canvas/bet/betPos/possifan/selfZhu").getComponent(cc.Label);

                var zerguo = cc.find("Canvas/bet/betPos/poserguo/tolalZhu").getComponent(cc.Label);
                var zduimen = cc.find("Canvas/bet/betPos/posduimen/tolalZhu").getComponent(cc.Label);
                var zsifan = cc.find("Canvas/bet/betPos/possifan/tolalZhu").getComponent(cc.Label);
                for (var i = 0; i < resultslist.length; i++) {
                    if (cc.vv.gameNetMgr.button == resultslist[i].seatindex) {
                        erguo.string = 0;
                        duimen.string = 0;
                        sifan.string = 0;
                        zerguo.string = resultslist[i].erguo;
                        zduimen.string = resultslist[i].duimen;
                        zsifan.string = resultslist[i].sifan;

                    } else {
                        erguo.string = resultslist[i].erguo;
                        duimen.string = resultslist[i].duimen;
                        sifan.string = resultslist[i].sifan;

                        zerguo.string = resultslist[0].erguo;
                        zduimen.string = resultslist[0].duimen;
                        zsifan.string = resultslist[0].sifan;
                    }
                }

            }, 500);
        }
    },
    onGameBeign: function (data) {
        this._kaiShi.active = true;
        this._guoZhuang.active = true;
    },

    initEventHandlers: function () {
        var self = this;
        cc.vv.gameNetMgr.dataEventHandler = this.node;
        this.node.on('game_sync', function (data) {
            console.log("game_sync");
            var dataSync = data.detail;
            var erguo = cc.find("Canvas/bet/betPos/poserguo/selfZhu").getComponent(cc.Label);
            var duimen = cc.find("Canvas/bet/betPos/posduimen/selfZhu").getComponent(cc.Label);
            var sifan = cc.find("Canvas/bet/betPos/possifan/selfZhu").getComponent(cc.Label);

            var zerguo = cc.find("Canvas/bet/betPos/poserguo/tolalZhu").getComponent(cc.Label);
            var zduimen = cc.find("Canvas/bet/betPos/posduimen/tolalZhu").getComponent(cc.Label);
            var zsifan = cc.find("Canvas/bet/betPos/possifan/tolalZhu").getComponent(cc.Label);
            for (var i in dataSync.seats) {
                if (dataSync.seats[i].userid == cc.vv.userMgr.userId) {
                    erguo.string = dataSync.seats[i].erguobet;
                    duimen.string = dataSync.seats[i].duimenbet;
                    sifan.string = dataSync.seats[i].sifanbet;

                    zerguo.string = dataSync.seats[i].zhuang.erguobet;
                    zduimen.string = dataSync.seats[i].zhuang.duimenbet;
                    zsifan.string = dataSync.seats[i].zhuang.sifanbet;
                }
            }


            if (dataSync.gameState) {
                if (dataSync.gamereadytime > 0) {
                    // self.countDown(dataSync, dataSync.gamereadytime);
                } else {
                    if (!dataSync.gamecardstate) {
                        if (cc.vv.gameNetMgr.seatIndex == cc.vv.gameNetMgr.button) {
                            self._kaiZhuangPai.active = true;
                        } else {
                            self._state.active = true;
                            self._state.getComponent(cc.Label).string = "请等待庄家开庄牌";
                        }
                    } else {
                        self.showAction(dataSync)
                    }
                }
            }
            cc.vv.common.initSeats();
        });

        this.node.on('game_begin', function (data) {
            console.log("game_begin");
            self._state.active = false;
            cc.vv.common.initSeats();
        });

        this.node.on('game_bet', function (data) {
            console.log("game_bet");
            self._kaiShi.active = false;
            self._guoZhuang.active = false;
            self._state.active = false;
            self._jishi = true;
            self._state.active = true;
            if (cc.vv.gameNetMgr.seatIndex == cc.vv.gameNetMgr.button) {
                self._state.getComponent(cc.Label).string = "等待闲家下注完成";
            } else {
                self._zhuma.active = true;
                self._state.getComponent(cc.Label).string = "点击注码后选择方位下注";
            }
            cc.vv.common.initSeats();
        });

        this.node.on('game_action', function (data) {
            console.log("game_action");
            cc.vv.common.initSeats();
            self.showAction(data.detail);
        });

        this.node.on('game_shuffle', function (data) {
            console.log("game_shuffle");
            if (cc.vv.gameNetMgr.seatIndex == data.detail) {
                self._kaiZhuangPai.active = true;
                self._state.active = false;
            } else {
                self._state.active = true;
                self._state.getComponent(cc.Label).string = "下注结束，等待庄家开庄牌！";
                self._zhuma.active = false;
            }
            var zhumachildren = cc.find('Canvas/bet/zhuma');
            for (var i = 0; i < zhumachildren.children.length; i++) {
                zhumachildren.children[i].color = cc.color(214, 214, 214);
            }
            cc.vv.common.initSeats();
        });

        this.node.on('game_guozhuang', function (data) {
            console.log("game_guozhuang");
            if (data.detail == cc.vv.userMgr.userId) {
                self._shangZhuang.active = false;
                self._guoZhuang.active = false;
                self._kaiShi.active = false;
                self._state.active = true;
                self._state.getComponent(cc.Label).string = "下庄后请等待其他玩家上庄";
            } else {
                self._shangZhuang.active = true;
                self._kaiShi.active = false;
                self._guoZhuang.active = false;
                self._state.active = false;
            }
        });

        this.node.on('game_start', function (data) {
            console.log("game_start");
            if (data.detail.buttonbool) {
                self._kaiShi.active = true;
                self._guoZhuang.active = true;
                self._shangZhuang.active = false;
                self._state.active = false;
            } else {
                self._shangZhuang.active = false;
                self._state.active = true;
                self._state.getComponent(cc.Label).string = "等待庄家开始";//已有玩家上庄，
            }
            cc.vv.common.initSeats();
        });

        this.node.on('game_total', function (data) {
            console.log("game_total");
            var erguo = cc.find("Canvas/bet/betPos/poserguo/tolalZhu").getComponent(cc.Label);
            var duimen = cc.find("Canvas/bet/betPos/posduimen/tolalZhu").getComponent(cc.Label);
            var sifan = cc.find("Canvas/bet/betPos/possifan/tolalZhu").getComponent(cc.Label);

            erguo.string = data.detail.returnErguo;
            duimen.string = data.detail.returnDuimen;
            sifan.string = data.detail.returnSifan;
            cc.vv.common.initSeats();
        });

        this.node.on('game_over', function (data) {
            console.log("game_over");
            var dataOver = data.detail.results;
            self.over(dataOver)
        });
    },
    over: function (dataOver) {
        var erguozhu = cc.find("Canvas/bet/betPos/poserguo/betZhu");
        var duimenbet = cc.find("Canvas/bet/betPos/posduimen/betZhu");
        var sifanbet = cc.find("Canvas/bet/betPos/possifan/betZhu");
        erguozhu.active = true;
        duimenbet.active = true;
        sifanbet.active = true;
        var erguo = erguozhu.getComponent(cc.Label);
        var duimen = duimenbet.getComponent(cc.Label);
        var sifan = sifanbet.getComponent(cc.Label);
        var seats = cc.vv.gameNetMgr.seats;
        for (var i = 0; i < seats.length; i++) {
            if (seats[i].userid != 0 && dataOver[i] != undefined) {
                if (dataOver[i].userId == cc.vv.userMgr.userId && dataOver[i].scoreCur) {
                    if (seats[i].seatindex == cc.vv.gameNetMgr.button) {
                        erguo.string = -dataOver[i].scoreCur.erguobet > 0 ? '+' + (-dataOver[i].scoreCur.erguobet) : -dataOver[i].scoreCur.erguobet;
                        duimen.string = -dataOver[i].scoreCur.duimenbet > 0 ? '+' + (-dataOver[i].scoreCur.duimenbet) : -dataOver[i].scoreCur.duimenbet;
                        sifan.string = -dataOver[i].scoreCur.sifanbet > 0 ? '+' + (-dataOver[i].scoreCur.sifanbet) : -dataOver[i].scoreCur.sifanbet;
                    } else {
                        erguo.string = dataOver[i].scoreCur.erguobet > 0 ? '+' + dataOver[i].scoreCur.erguobet : dataOver[i].scoreCur.erguobet;
                        duimen.string = dataOver[i].scoreCur.duimenbet > 0 ? '+' + dataOver[i].scoreCur.duimenbet : dataOver[i].scoreCur.duimenbet;
                        sifan.string = dataOver[i].scoreCur.sifanbet > 0 ? '+' + dataOver[i].scoreCur.sifanbet : dataOver[i].scoreCur.sifanbet;
                    }
                }
            }
        }

    },
    showAction: function (data) {
        console.log(data)
        cc.vv.common.initSeats();
        this._randomCard = data.randomCard;
        this._kaiZhuangPai.active = false;
        this._zhuangPai.active = true;
        var _this = this;
        var pokergame = cc.find("Canvas/game");
        var zhuangPai = this._zhuangPai.getComponent(cc.Sprite);
        zhuangPai.spriteFrame = cc.vv.pokerMgr.getSpriteFrameByPKID(data.zhuangCard);
        var index = (data.zhuangCard % 13 == 0 ? 13 : data.zhuangCard % 13) % 4
        var state = true;

        var jumpX = cc.vv.gameNetMgr.conf.type == "nn" ? [-80, -40, 0, 40, 80] : [-20, 20];
        var jumpY = [154, 0, -154, 0];
        var typeNum = cc.vv.gameNetMgr.conf.type == "nn" ? 5 : 2;
        var _this = this;
        var aaa = []
        for (var i = 1; i < 5; i++) {
            aaa[i - 1] = []
            for (var j = 1; j < (typeNum + 1); j++) {
                aaa[i - 1][j - 1] = 0.5 + i * 0.1
            }
        }
        var len = index + pokergame.children.length
        for (var i = index; i < len; i++) {
            var mo = i % 4;
            for (var j = 0; j < pokergame.children[mo].children.length; j++) {
                if (j < typeNum) {
                    var str = 0;
                    if (mo == 0 || mo == 2) {
                        str = jumpX[j];
                    } else if (mo == 1) {
                        str = jumpX[j] - 300;
                    } else {
                        str = jumpX[j] + 300;
                    }
                    var painode = pokergame.children[mo].children[j]
                    var pai = data.randomCard[mo][j];
                    var pokerSprites = painode.getComponent(cc.Sprite);
                    pokerSprites.spriteFrame = cc.vv.pokerMgr.getSpriteFrameByPKID(pai);
                    painode.active = true;
                    painode.runAction(cc.repeat(cc.moveTo(1 * aaa[i - index][j], cc.p(str, jumpY[mo])), 1));
                }
            }
        }

        var directorname = cc.vv.gameNetMgr.conf.type == 'nn' ? 'nngame' : 'jdbgame'
        setTimeout(function () {
            var timerSpot = null;
            var audioNum = -1;
            timerSpot = setInterval(function () {
                if (cc.director.getScene().name == directorname) {
                    audioNum++;
                    if (audioNum < 4) {
                        var paidianSpot = _this._randomCard[audioNum];
                        var spot = pokergame.children[audioNum].children[pokergame.children[audioNum].children.length - 1];
                        spot.active = true;
                        var spotSprite = spot.getComponent(cc.Label);
                        spotSprite.string = cc.vv.pokerMgr.getSpriteFrameByPD(paidianSpot[paidianSpot.length - 1]);
                        var audioUrl = cc.vv.pokerMgr.getAudioURLByNNID(paidianSpot[paidianSpot.length - 1]);
                        cc.vv.audioMgr.playSFX(audioUrl);
                    } else {
                        clearInterval(timerSpot);
                        audioNum = -1;
                        if (cc.vv.replayMgr.isReplay()) {
                            _this.over(cc.vv.gameNetMgr.resultslist);
                        }
                    }
                } else {
                    clearInterval(timerSpot)
                }
            }, 1000);
        }, 4000);
    },

    onBtnShangzhuangClicked: function (event) {
        cc.vv.net.send("startzhuang");
    },

    onBtnGuozhuangClicked: function (event) {
        cc.vv.net.send("endzhuang");
    },

    onBtnKaishiClicked: function (event) {
        cc.vv.net.send("pokerready", cc.vv.gameNetMgr.roomId);
    },

    onBtnKaizhuangpaiClicked: function (event) {
        cc.vv.net.send("pokerbegin", cc.vv.userMgr.userId);
    },

    onBtnBetClicked: function (event) {
        if (!cc.vv.timePointer._betbool) {
            return;
        }
        if (cc.vv.gameNetMgr.seatIndex == cc.vv.gameNetMgr.button) {
            return;
        }
        var xian = cc.find("Canvas/bet/betPos/" + event.target.name).getChildByName('selfZhu').getComponent(cc.Label);
        xian.string = parseInt(xian.string) + parseInt(cc.vv.timePointer._zhuNum);
    },

    onBetzhuClicked: function (event) {
        if (!cc.vv.timePointer._betbool) {
            return;
        }
        cc.vv.timePointer._zhuNum = event.target.name.substring(event.target.name.indexOf("_") + 1, event.target.name.length);
        var zhumachildren = cc.find('Canvas/bet/zhuma');
        for (var i = 0; i < zhumachildren.children.length; i++) {
            if (zhumachildren.children[i].name == event.target.name) {
                zhumachildren.children[i].color = cc.color(255, 255, 255);
            } else {
                zhumachildren.children[i].color = cc.color(214, 214, 214);
            }
        }
    },

    onBtnExit: function () {//解散
        console.log("试试");
    }
});
